/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jmooc.servlets;

import com.jmooc.entity.User;
import com.jmooc.service.UserService;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Group
 */
@WebServlet(name = "RegisterServlet", urlPatterns = {"/register"})
public class RegisterServlet extends HttpServlet {

    @EJB
    private UserService userService;
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mail = req.getParameter("email");
        String password = req.getParameter("password");
        String passwordConfirm = req.getParameter("passwordConfirm");
        String firstName = "Prénom";
        String lastName = "Nom";
        
        if (!mail.equals("") && !password.equals("") && password.equals(passwordConfirm)) {
            try {
                User u = new User();
                u.setEmail(mail);
                u.setPassword(password);
                u.setFirstName(firstName);
                u.setLastName(lastName);
                userService.create(u);
                
                req.getSession().setAttribute("message", "Vous êtes enregistré ! Vous pouvez vous connecter");
                resp.sendRedirect(req.getServletContext().getContextPath() + "/login");
                return;
            } catch (Exception e) {
            }
        }
        
        req.setAttribute("message", "Addresse mail déjà existante ou mauvaise confirmation de mot de passe");
        RequestDispatcher rd = req.getRequestDispatcher("/jsp/register.jsp");
        rd.forward(req, resp);    
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                HttpSession session = req.getSession();
                session.removeAttribute("message");
        RequestDispatcher rd = req.getRequestDispatcher("/jsp/register.jsp");
        rd.forward(req, resp);
    }
}
